package org.porkbelly.date;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

/**
 * <p>
 * PIG's default ToDate function uses Joda time to parse the date. Since Joda
 * time doesn't support 3 character time zone, it forces users to strip the
 * zone and then pass it separately. To make it easier, this function uses
 * Java's SimpleDateFormat to parse dates with 3 character time zone.</p>
 * <p>Example: 20131201 10:10:10 UTC</p>
 * <p>The date must be in the format "yyyyMMdd HH:mm:ss z"</p>
 * 
 * @author peter lin
 *
 */
public class ToDate extends EvalFunc<DateTime> {
	
    private static final SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("yyyyMMdd HH:mm:ss z");

    public ToDate() {
    	super();
    }
    
    public DateTime exec(Tuple input) throws IOException {
        if (input == null || input.size() < 1 || input.get(0) == null) {
            return null;
        }
        String dateString = (String)input.get(0);
        try {
			java.util.Date d = simpleDateFormatter.parse(dateString.trim());
	        return new DateTime(d.getTime());
		} catch (ParseException e) {
			log.equals("Date was not in yyyyMMdd HH:mm:ss z format");
	        return null;
		}
    }

    @Override
    public Schema outputSchema(Schema input) {
        return new Schema(new Schema.FieldSchema(getSchemaName(this.getClass()
                .getName().toLowerCase(), input), DataType.DATETIME));
    }

    public static DateTimeZone extractDateTimeZone(String dtStr) {
        try {
			java.util.Date d = simpleDateFormatter.parse(dtStr.trim());
	        return new DateTime(d.getTime()).getZone();
		} catch (ParseException e) {
	        return null;
		}
    }

    public static DateTime extractDateTime(String dtStr) {
        try {
			java.util.Date d = simpleDateFormatter.parse(dtStr.trim());
	        return new DateTime(d.getTime());
		} catch (ParseException e) {
	        return null;
		}
    }
}
